<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header :addTodo="addTodo"/>
      <List :todoList="todos" :deleteTodo="deleteTodo" :changeTodoChecked="changeTodoChecked"/>
      <Footer :todoList="todos" :changeAllTodoChecked="changeAllTodoChecked" :deleteSelectedChecked="deleteSelectedChecked"/>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header";
import List from "@/components/List";
import Footer from "@/components/Footer";
export default {
  name: "App",
  components:{
    Header,
    List,
    Footer
  },
  data(){
    return{
      //数据
      todos:sessionStorage.todos? JSON.parse(sessionStorage.todos):[]
    }
  },
  updated() {
    sessionStorage.setItem('todos',JSON.stringify(this.todos))
  },
  methods:{
    //添加todo
    addTodo(msg){
      if(!msg){
        return alert('请输入标题！')
      }
      const title = msg.trim()
      if(!title){
        return alert('不能输入空标题！')
      }
      this.todos.unshift({
        id:Math.random().toString(36).slice(2),
        title,
        done:false
      })
    },
  //  删除todo
    deleteTodo(id){
      this.todos = this.todos.filter(item=>item.id!==id)
    },
  //  修改单个todo的状态
    changeTodoChecked(id){
      this.todos = this.todos.map(item=>{
        if(item.id===id){
          item.done = !item.done
        }
        return item
      })
    },
  //  修改所有todo的选中状态
    changeAllTodoChecked(val){
      this.todos = this.todos.map(item=>{
        item.done = val
        return item
      })
    },
  //  清除已完成的todo
    deleteSelectedChecked(){
      this.todos = this.todos.filter(item=>!item.done)
    }
  }
}
</script>

<style>
@import "@/assets/css/App.css";
</style>